package com.cl.oauth.core.resource.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Set;

/**
 * 权限认证管理器，用于判断操作是否有资源访问的权限
 */
@Component
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Autowired
    AuthorizationProperties authorizationProperties;
    @Autowired
    PermitProperties permitProperties;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();

        return Mono.just(new AuthorizationDecision(true));
        //对应跨域的预检请求直接放行
//        if (request.getMethod() == HttpMethod.OPTIONS) {
//            return Mono.just(new AuthorizationDecision(true));
//        }
//
//        // 是否属于需要放行的资源
//        if(permitProperties.permit(request.getURI().getPath())) {
//            return Mono.just(new AuthorizationDecision(true));
//        }
//
//
//        // todo 获取当前的请求路径需要的权限
//        String method = request.getMethod() == null ? "GEY" : request.getMethod().name();
//        Set<String> permissions = authorizationProperties.getRequestNeedPermission(request.getURI().getPath(), method);
//
//        //认证通过且角色匹配的用户可访问当前路径
//        //                    return authorizationProperties.contains(roleId);
//        // 这里可能没有处理完。
//        return authentication
//                .filter(Authentication::isAuthenticated)
//                .flatMapIterable(Authentication::getAuthorities)
//                .map(GrantedAuthority::getAuthority)
//                .any(permissions::contains)
//                .map(AuthorizationDecision::new)
//                .defaultIfEmpty(new AuthorizationDecision(false));
    }
}
